package com.hmdp.service.impl;

import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.core.lang.UUID;
import com.hmdp.service.ILock;
import lombok.RequiredArgsConstructor;
import org.springframework.core.io.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;


import java.util.Collections;
import java.util.concurrent.TimeUnit;

@RequiredArgsConstructor
public class SimpleRedisLock implements ILock{
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;
    static {
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation((Resource) new ClassPathResource("unlock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }





    //业务名称
    private  final String name;
    //锁的key前缀
    private  final String KEY_PREFIX = "lock:";
    //线程标识 toString("true") 去掉符号UUID的-
    private  final String ID_PREFIX = UUID.randomUUID().toString(true)+"-";
    private  final StringRedisTemplate  stringRedisTemplate;
    //注意事项：设置锁的名称应该与业务相关，不能将锁名称写死，不能让所有业务获取同一把锁
    //  锁的业务应该与锁的名称相关，不同的业务获取不同的锁
    @Override
    public boolean tryLock(long timeoutSec) {
        //  获取锁的key值
        String key = KEY_PREFIX + name;
        //  获取当前线程的id，作为线程标识，可以识别哪个线程拿到的锁
        String value = ID_PREFIX + Thread.currentThread().getId();
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, value, timeoutSec, TimeUnit.SECONDS);
        //自动拆箱可能导致空指针，因此使用工具类判断
        return Boolean.TRUE.equals(flag);
    }

    @Override
    /*public void unlock() {
        //获取线程标识
        String value = ID_PREFIX + Thread.currentThread().getId();
        //获取锁中的标识
        String id = stringRedisTemplate.opsForValue().get(KEY_PREFIX + name);
        //判断标识是否一致
        if (value.equals(id)) {
            //一致，释放锁
            stringRedisTemplate.delete(KEY_PREFIX + name);
        }
    }*/
    public void unlock() {
        //调用Lua脚本
        stringRedisTemplate.execute(
                UNLOCK_SCRIPT, Collections.singletonList(KEY_PREFIX + name),
                ID_PREFIX + Thread.currentThread().getId()
        );
    }
}
